package com.jml.spring.springboot.tomcat;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixContextListener;

//自己java创建tomcat
public class CreateTomcat {

	private static int PORT=8080;
	private static String CONTEXT_PATH="/jml";
	private static String SERVLET_NAME="indexServletUrl";//这个名字随意起的相当于servlet标签的servlet-name

	public static void main(String[] args) throws Exception {
		//创建tomcat服务器
		Tomcat tomcatServer = new Tomcat();
		//指定端口号
		tomcatServer.setPort(PORT);
		//是否设置自动部署
		tomcatServer.getHost().setAutoDeploy(false);
		//创建上下文
		StandardContext standardContext = new StandardContext();
		//通过上下文设置访问地址
		standardContext.setPath(CONTEXT_PATH);
		//监听上下文
		standardContext.addLifecycleListener(new FixContextListener());
		//将tomcat添加上下文
		tomcatServer.getHost().addChild(standardContext);
		//-------------------------这段代码等价于web.xml标签中的servlet标签
		//创建servlet
		tomcatServer.addServlet(CONTEXT_PATH,SERVLET_NAME,new IndexServlet());
		//指定url映射   /index相当于servlet标签的  url-pattern
		standardContext.addServletMappingDecoded("/index", SERVLET_NAME);
		//-------------------------

		//启动tomcat
		tomcatServer.start();
		//异步进行接收请求
		tomcatServer.getServer().await();
		System.out.println("jml·s tomcat start success");

	}

}
